package com.lyl.security.common.config;

import com.lyl.security.common.exception.BizException;
import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Object> onMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return Result.build(ErrorCode.METHOD_NOT_SUPPORT);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Object> onHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return Result.build(ErrorCode.POST_REQUEST_BODY_NOT_JSON);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BizException.class)
    public Result<Object> onBizException(BizException e) {
        log.error("业务异常", e);
        return Result.build(e.getBizCode()).setMsg(e.getMsg());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public Result<Object> onAuthenticationException(AuthenticationException e) {
        log.error("认证异常", e);
        return Result.build(ErrorCode.UNAUTHORIZED, e.getMessage());
    }


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<Object> onException(Exception e) {
        log.error("系统异常", e);
        return Result.build(ErrorCode.SYSTEM_ERROR);
    }
}
